package com.xz.usercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xz.usercenter.common.BaseResponse;
import com.xz.usercenter.common.ErrorCode;
import com.xz.usercenter.common.ResultUtil;
import com.xz.usercenter.exception.BusinessException;
import com.xz.usercenter.model.domain.User;
import com.xz.usercenter.model.domain.request.UserLoginRequest;
import com.xz.usercenter.model.domain.request.UserRegisterRequest;
import com.xz.usercenter.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.xz.usercenter.constant.UserConstant.*;

/**
 * @author 徐洲
 * @version 1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest){
        if (userRegisterRequest == null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String verificationCode = userRegisterRequest.getVerificationCode();
        if (StringUtils.isAllBlank(userAccount, userPassword, checkPassword, verificationCode)){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword, verificationCode);
        return ResultUtil.success(result);
    }

    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request){
        if(userLoginRequest == null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAllBlank(userAccount, userPassword)){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtil.success(user);
    }

    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request){
        if (request == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }

        if (userService.userLogout(request) != 1){
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return ResultUtil.success();
    }

    @GetMapping ("/search")
    public BaseResponse<List<User>> userSearch(String userName, HttpServletRequest request){
        if (!isAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        LambdaQueryWrapper<User> userQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNoneBlank(userName)){
            userQueryWrapper.like(User::getUserName, userName);
        }
        List<User> userList = userService.list(userQueryWrapper);
        List<User> list = userList.stream().map((user) -> userService.getSafetyUser(user)).collect(Collectors.toList());
        return ResultUtil.success(list);
    }

    @DeleteMapping
    public BaseResponse<Boolean> userDelete(@RequestParam List<Long> ids, HttpServletRequest request){
        if (ids == null || ids.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (ids.stream().anyMatch(id -> id <= 0)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (!isAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        boolean b = userService.removeBatchByIds(ids);
        return ResultUtil.success(b);
    }

    /**
     * 获取用户当前登录状态
     *
     * @param request
     * @return
     */
    @GetMapping("/current")
    private BaseResponse<User> getCurrentUser(HttpServletRequest request){
        Object attribute = request.getSession().getAttribute(USER_LOGIN_STATUS);
        User currentUser = (User) attribute;
        if (currentUser == null){
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        Long userId = currentUser.getId();
        User user = userService.getById(userId);
        User safetyUser = userService.getSafetyUser(user);
        return ResultUtil.success(safetyUser);
    }


    /**
     * 判读用户是否是管理员
     */
    private boolean isAdmin(HttpServletRequest request){
        Object attribute = request.getSession().getAttribute(USER_LOGIN_STATUS);
        User user = (User) attribute;
        return user != null && Objects.equals(user.getUserRole(), USER_ADMIN_ROLE);
    }
}
